<template>
  <div class="users">
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <div style="margin-top: 15px;">
        <el-row :gutter="20">
          <!-- gutter 间隙 row行 col 列 都是elementUI的栅格系统 -->
          <el-col :span="8">
            <el-input
              :clearable="true"
              placeholder="请输入内容"
              @clear="getUserList"
              v-model="queryInfo.query">
              <el-button slot="append" icon="el-icon-search" @click="getUserList()"></el-button>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
          </el-col>
        </el-row>
      </div>
      <!-- 用户列表区域 -->
      <el-table
        :data="userData" stripe style="width: 100%" border>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <!-- v-slot的是属性在2.5.0版本代替了scope-slot scope是自定义的 当前行的数据 -->
          <template v-slot="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChanged(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template v-slot="scope">
            <!-- 修改按钮 -->
            <el-tooltip class="item" effect="dark" :enterable="false" content="修改" placement="top">
              <el-button @click="setUserB(scope.row.id)" type="primary" size="mini" icon="el-icon-edit"></el-button>
            </el-tooltip>
            <!-- 删除按钮 -->
            <el-tooltip class="item" effect="dark" :enterable="false" content="删除" placement="top">
              <el-button @click="setDeletUser(scope.row.id)" type="danger" size="mini" icon="el-icon-delete"></el-button>
            </el-tooltip>
            <!-- 分配权限按钮 -->
            <el-tooltip class="item" effect="dark" :enterable="false" content="分配权限" placement="top">
              <el-button type="warning" size="mini" icon="el-icon-setting"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        style="marginTop:15px"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>

      <!-- 添加用户对话框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addDialogClosed"
        >
        <!-- 内容主题区域 -->
        <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
        class="demo-ruleForm">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改用户对话框 -->
       <el-dialog
        title="修改用户"
        :visible.sync="setDialogVisible"
        width="50%"
        >
        <!-- 内容主题区域 -->
        <el-form
        :model="setForm"
        :rules="setFormRules"
        ref="setFormRef"
        label-width="70px"
        class="demo-ruleForm">
          <el-form-item label="用户名" prop="username">
            <el-input disabled v-model="setForm.username"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="setForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="setForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="setUser">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 确认删除弹窗 -->
      <el-dialog
        title="提示"
        :visible.sync="deleteDialogVisible"
        width="30%"
        >
        <span>你确定要<b style="color: red">删除吗？</b></span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="deleteUser()">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { login, addUsers, getUsers, setUsers, deleteUsers } from '@/api/user'
export default {
  name: 'Users',
  data () {
    // 验证邮箱
    var checkEmail = (rules, value, cb) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    return {
      // 获取用户列表的参数
      queryInfo: {
        query: '',
        pagenum: 1,
        // 当前的页数
        pagesize: 2
        // 当前每页显示多少条数据
      },
      // 用户数据
      userData: [],
      total: 0,
      tableData: [{
        date: '2016-05-02',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1518 弄'
      }, {
        date: '2016-05-04',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1517 弄'
      }, {
        date: '2016-05-01',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1519 弄'
      }, {
        date: '2016-05-03',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1516 弄'
      }],
      searchData: '',
      addDialogVisible: false, // 控制添加对话框的显示和隐藏
      setDialogVisible: false, // 控制修改对话框
      deleteDialogVisible: false, // 控制删除用户对话框
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      }, // 添加用户的表单数据
      setForm: {
        username: '',
        email: '',
        mobile: '',
        id: ''
      },
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名在3-10之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 10, message: '密码在3-10之间', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入mobile', trigger: 'blur' },
          { min: 3, max: 10, message: '邮箱在3-10之间', trigger: 'blur' }
        ]
      }, // 添加表单的验规则对象
      setFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入mobile', trigger: 'blur' },
          { min: 3, max: 10, message: '邮箱在3-10之间', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getUserList()
    console.log(this.$refs)
    login('admin', '123456')
      .then(res => {
        console.log('我是测试', res)
      })
  },
  methods: {
    // 根据 data 里面 的userInfo 请求数据
    async getUserList () {
      // 注意参数的获取形式
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      if (res.meta.status !== 200) {
        return this.$message.error('获取列表失败！')
      }
      this.userData = res.data.users
      this.total = res.data.total
    },
    // 监听 pageSize  页面改变事件
    handleSizeChange (newSize) {
      // console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听 页码 改变事件
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 监听 switch 开发
    async userStateChanged (userinfo) {
      // 修改状态
      const { data: res } = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error('跟新用户状态失败！')
      }
      this.$message.success('跟新用户状态成功！')
    },
    // 监听用户对框的关闭事件事件
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 添加用户
    addUser () {
      this.addDialogVisible = false
      // 判断是否有问题
      this.$refs.addFormRef.validate(item => {
        if (item !== false) {
          this.$message.success('添加用户成功！')
          addUsers(this.addForm)
            .then(res => {
              console.log(res)
            })
          this.getUserList()
        } else {
          this.$message.error('添加用户失败！')
        }
      })
    },
    // 修改用户
    setUser () {
      this.setDialogVisible = false
      this.$refs.setFormRef.validate(item => {
        if (item !== false) {
          // setUsers(this.setForm)
          setUsers(this.setForm)
            .then(res => {
              console.log(res)
              this.$message.success('修改用户成功！')
              this.getUserList()
            })
        }
      })
    },
    // 修改用户表单赋值
    setUserB (value) {
      // 拿到数据 赋值
      console.log(value)
      getUsers(value)
        .then(res => {
          console.log(res)
          this.setForm = res.data
          this.setDialogVisible = true
        })
    },
    // 设置删除框显示
    setDeletUser (id) {
      getUsers(id)
        .then(res => {
          console.log(res)
          this.setForm = res.data
          this.deleteDialogVisible = true
        })
    },
    // 确认删除用户
    deleteUser () {
      this.deleteDialogVisible = false
      console.log(this.setForm.id)
      deleteUsers(this.setForm.id)
        .then(res => {
          console.log(res)
          this.$message.success('删除用户成功！')
          this.getUserList()
        })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
